<template>
  <div class="goods-management">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button @click="fetchGoods">刷新</el-button>
    </div>

    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px" layout="inline">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.title" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商家ID">
          <el-input v-model="searchForm.shopId" placeholder="请输入商家ID" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="0" />
            <el-option label="已上架" value="1" />
            <el-option label="审核拒绝" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="goodsList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="gid" label="商品ID" width="80" />
        <el-table-column prop="title" label="商品名称" min-width="150" />
        <el-table-column prop="shop_id" label="商家ID" width="100" />
        <el-table-column prop="g_price" label="价格(元)" width="100" align="center">
          <template #default="scope">
            ¥{{ scope.row.g_price }}
          </template>
        </el-table-column>
        <el-table-column prop="stock_quantity" label="库存" width="80" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.isOnline)">
              {{ getStatusText(scope.row.isOnline) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewGoods(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.isOnline === 0" 
              size="small" 
              type="success" 
              @click="approveGoods(scope.row)"
            >
              通过
            </el-button>
            <el-button 
              v-if="scope.row.isOnline === 0" 
              size="small" 
              type="danger" 
              @click="rejectGoods(scope.row)"
              style="margin-left: 5px;"
            >
              拒绝
            </el-button>
            <el-button 
              v-if="scope.row.isOnline === 1" 
              size="small" 
              type="warning" 
              @click="offlineGoods(scope.row)"
            >
              下架
            </el-button>
            <el-button 
              v-if="scope.row.isOnline === 0 || scope.row.isOnline === 2" 
              size="small" 
              type="success" 
              @click="onlineGoods(scope.row)"
            >
              上架
            </el-button>
            <el-button 
              v-if="scope.row.isOnline !== 1" 
              size="small" 
              type="danger" 
              @click="deleteGoods(scope.row)"
              style="margin-left: 5px;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 商品详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="'商品详情 - ' + currentGoods.title" width="600px">
      <el-form :model="currentGoods" label-width="100px">
        <el-form-item label="商品ID">
          <span>{{ currentGoods.gid }}</span>
        </el-form-item>
        <el-form-item label="商品名称">
          <span>{{ currentGoods.title }}</span>
        </el-form-item>
        <el-form-item label="商家ID">
          <span>{{ currentGoods.shop_id }}</span>
        </el-form-item>
        <el-form-item label="价格">
          <span>¥{{ currentGoods.g_price }}</span>
        </el-form-item>
        <el-form-item label="库存">
          <span>{{ currentGoods.stock_quantity }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="getStatusTagType(currentGoods.isOnline)">
            {{ getStatusText(currentGoods.isOnline) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="商品描述">
          <span>{{ currentGoods.description }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核意见对话框 -->
    <el-dialog v-model="auditDialogVisible" :title="auditDialogTitle" width="500px">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item :label="auditOpinionLabel">
          <el-input 
            v-model="auditForm.opinion" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGoodsListAPI, approveGoodsAPI, rejectGoodsAPI, offlineGoodsAPI, onlineGoodsAPI, getGoodsDetailAPI, deleteGoodsAPI } from '@/apis/adminGoods'

const goodsList = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const auditDialogTitle = ref('')
const auditOpinionLabel = ref('')
const currentGoods = ref({})
const currentAction = ref('') // 'approve', 'reject', 'offline'

const searchForm = reactive({
  title: '',
  shopId: '',
  status: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const auditForm = reactive({
  opinion: ''
})

onMounted(() => {
  fetchGoods()
})

const fetchGoods = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      title: searchForm.title || undefined,
      shopId: searchForm.shopId || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await getGoodsListAPI(params)
    
    if (response.code === 200) {
      goodsList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchGoods()
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.shopId = ''
  searchForm.status = ''
  pagination.currentPage = 1
  fetchGoods()
}

const viewGoods = async (goods) => {
  try {
    const response = await getGoodsDetailAPI(goods.gid)
    if (response.code === 200) {
      currentGoods.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取商品详情失败')
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + error.message)
  }
}

const approveGoods = (goods) => {
  currentGoods.value = { ...goods }
  currentAction.value = 'approve'
  auditDialogTitle.value = '通过商品审核'
  auditOpinionLabel.value = '通过意见'
  auditForm.opinion = '审核通过，商品可以提交上架申请'
  auditDialogVisible.value = true
}

const rejectGoods = (goods) => {
  currentGoods.value = { ...goods }
  currentAction.value = 'reject'
  auditDialogTitle.value = '拒绝商品审核'
  auditOpinionLabel.value = '拒绝原因'
  auditForm.opinion = '商品信息不符合要求，审核拒绝'
  auditDialogVisible.value = true
}

const offlineGoods = (goods) => {
  currentGoods.value = { ...goods }
  currentAction.value = 'offline'
  auditDialogTitle.value = '商品下架'
  auditOpinionLabel.value = '下架原因'
  auditForm.opinion = '根据平台规定，商品需要下架处理'
  auditDialogVisible.value = true
}

const onlineGoods = (goods) => {
  currentGoods.value = { ...goods }
  currentAction.value = 'online'
  auditDialogTitle.value = '商品上架'
  auditOpinionLabel.value = '上架原因'
  auditForm.opinion = '根据平台规定，商品可以上架销售'
  auditDialogVisible.value = true
}

const deleteGoods = (goods) => {
  currentGoods.value = { ...goods }
  currentAction.value = 'delete'
  auditDialogTitle.value = '删除商品'
  auditOpinionLabel.value = '删除原因'
  auditForm.opinion = '根据平台规定，商品需要删除处理'
  auditDialogVisible.value = true
}

const submitAudit = async () => {
  try {
    let response;
    switch (currentAction.value) {
      case 'approve':
        response = await approveGoodsAPI(currentGoods.value.gid, auditForm.opinion)
        break
      case 'reject':
        response = await rejectGoodsAPI(currentGoods.value.gid, auditForm.opinion)
        break
      case 'offline':
        response = await offlineGoodsAPI(currentGoods.value.gid, auditForm.opinion)
        break
      case 'online':
        response = await onlineGoodsAPI(currentGoods.value.gid, auditForm.opinion)
        break
      case 'delete':
        response = await deleteGoodsAPI(currentGoods.value.gid, auditForm.opinion)
        break
      default:
        throw new Error('未知操作类型')
    }
    
    if (response.code === 200) {
      ElMessage.success(response.message || '操作成功')
      auditDialogVisible.value = false
      fetchGoods() // 刷新列表
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchGoods()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchGoods()
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已上架',
    2: '审核拒绝'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}
</script>

<style scoped>
.goods-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>